import AnimatedObject from '../base/animated_object';

const BULLET_IMG_PREFIX = 'graphics/Bullets/PeaNormal/PeaNormal_';
const BULLET_FRAME_COUNT = 1;
const BULLET_WIDTH = 56;
const BULLET_HEIGHT = 34;

export default class Bullet extends AnimatedObject {
  constructor() {
    super(BULLET_IMG_PREFIX, BULLET_FRAME_COUNT, BULLET_WIDTH, BULLET_HEIGHT);
    this.damage = 40; // 初始伤害值为40
  }

  init(x, y, speed, damage=40) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.damage = damage;
    this.isActive = true;
    this.visible = true;
  }

  // 每一帧更新子弹位置
  update() {
    super.update(); // 更新动画帧
    this.x += this.speed; // 向右移动
    
    // 检测与僵尸的碰撞
    this.checkCollisionWithZombies();
    
    // 超出屏幕外销毁
    if (this.x > canvas.width) {
      this.destroy();
    }
  }
  
  // 检测与僵尸的碰撞
  checkCollisionWithZombies() {
    const zombies = GameGlobal.zombieManager ? GameGlobal.zombieManager.zombies : [];
    
    for (let i = zombies.length - 1; i >= 0; i--) {
      const zombie = zombies[i];
      
      // 检查僵尸是否存活
      if (zombie.isDead) continue;
      
      // 使用isCollideWith方法检测碰撞
      if (this.isCollideWith(zombie)) {
        // 碰撞发生
        zombie.takeDamage(this.damage);
        this.destroy();
        break;
      }
    }
  }

  destroy() {
    this.isActive = false;
    // 子弹没有销毁动画，直接移除
    this.remove();
  }

  remove() {
    this.isActive = false;
    this.visible = false;
    // 回收子弹对象
    GameGlobal.databus.removeBullets(this);
  }
}
